package com.freewater.javabase.demo.network.uri;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;

public class URLDemo {
    public static void main(String[] args) throws URISyntaxException, IOException {
        URI uri = new URI("https://www.baidu.com/s?wd=人工智能");
        // 未编码的uri字符串表示
        System.out.println(uri);// https://www.baidu.com/s?wd=人工智能
        // 编码后的uri标识
        System.out.println(uri.toASCIIString()); // https://www.baidu.com/s?wd=%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD
        URL url = uri.toURL();
        final InputStream inputStream = url.openStream();
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int count;
        while ((count = inputStream.read(bytes)) != -1) {
            bos.write(bytes, 0, count);
        }
        bos.flush();
        inputStream.close();
        bos.close();
        System.out.println(bos.toString(Charset.forName("utf-8")).substring(0, 100));
    }
}
